package com.example.clickhouse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import ru.yandex.clickhouse.ClickHouseConnection;
import ru.yandex.clickhouse.ClickHouseDataSource;
import ru.yandex.clickhouse.settings.ClickHouseProperties;

import java.sql.PreparedStatement;

@Service
public class ClickHouseService {

    @Value("${clickhouse.url}")
    private String url;

    @Value("${clickhouse.username}")
    private String username;

    @Value("${clickhouse.password}")
    private String password;

    public void insertData(String data) {
        ClickHouseProperties properties = new ClickHouseProperties();
        properties.setUser(username);
        properties.setPassword(password);

        ClickHouseDataSource dataSource = new ClickHouseDataSource(url, properties);
        try (ClickHouseConnection connection = dataSource.getConnection();
             PreparedStatement statement = connection.prepareStatement(
                     "INSERT INTO processed_data (message) VALUES (?)")) {
            statement.setString(1, data);
            statement.execute();
            System.out.println("Inserted into ClickHouse: " + data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}